package cn.itcast.controller.log;


import cn.itcast.domain.system.SysLog;
import cn.itcast.domain.system.User;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.UUID;

@Component
@Aspect
public class LogAspect {

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private HttpSession session;

    @Around("execution(* cn.itcast.controller.*.*.*(..))")
    public Object saveLog(ProceedingJoinPoint pjp) throws Throwable {
        Object result = null;



            result = pjp.proceed();
            SysLog sysLog = new SysLog();

            sysLog.setId(UUID.randomUUID().toString());
            sysLog.setTime(new Date());

            String ip = request.getRemoteAddr();
            sysLog.setIp(ip);

            User user = (User) session.getAttribute("loginUser");
            sysLog.setUserName(user.getUserName());
            sysLog.setCompanyId(user.getCompanyId());
            sysLog.setCompanyName(user.getCompanyName());


            MethodSignature signature = (MethodSignature) pjp.getSignature();//获取方法签名,方法名+注解
            Method method = signature.getMethod();//获取方法
            String name = method.getName();//获取方法名称
            sysLog.setMethod(name);

            if (method.isAnnotationPresent(RequestMapping.class)) {
                RequestMapping annotation = method.getAnnotation(RequestMapping.class);
                sysLog.setAction(annotation.name());//取得是方法上@RequestMapping的注解中name对应的值
            }



        return result;
    }
}
